'use strict';

exports.main = async (event, context) => {
	const { courseId, userId } = event;
	
	if (!userId) {
		return {
			code: -1,
			message: '用户未登录'
		}
	}
	
	if (!courseId) {
		return {
			code: -1,
			message: '课程ID不能为空'
		}
	}
	
	const db = uniCloud.database();
	const tripCollection = db.collection('trips');
	
	try {
		// 检查是否已经添加过该课程
		const existRes = await tripCollection.where({
			userId: userId,
			courseId: courseId
		}).get();
		
		if (existRes.data.length > 0) {
			return {
				code: -1,
				message: '该课程已在行程中'
			}
		}
		
		// 添加行程
		const addRes = await tripCollection.add({
			userId: userId,
			courseId: courseId,
			status: 0,
			createTime: Date.now(),
			updateTime: Date.now()
		});
		
		return {
			code: 0,
			message: '添加成功',
			data: {
				tripId: addRes.id
			}
		}
	} catch (error) {
		return {
			code: -1,
			message: '添加失败'
		}
	}
}; 